import React, { useEffect, useState } from 'react'
import './Data.css'
import { Bar, BarChart, CartesianGrid, Line, LineChart, RadialBar, RadialBarChart, ResponsiveContainer, Tooltip, XAxis } from 'recharts'

const DatePill: React.FC<{ day: string; month: string; active?: boolean; onClick?: () => void }> = ({ day, month, active, onClick }) => {
  return (
    <div className={`date-pill${active ? ' active' : ''}`} onClick={onClick}>
      <div className="date-pill-day">{day}</div>
      <div className="date-pill-month">{month}</div>
    </div>
  )
}

const Card: React.FC<React.PropsWithChildren<{ title: string; icon?: React.ReactNode }>> = ({ title, icon, children }) => {
  return (
    <div className="card">
      <div className="card-header">
        <span className="card-title">{title}</span>
        <span className="card-icon">{icon}</span>
      </div>
      <div className="card-body">{children}</div>
    </div>
  )
}

// helpers to create demo data per selected date
const generateDashboardData = (seed: number) => {
  const random = (min: number, max: number) => {
    const x = Math.sin(seed++) * 10000
    const frac = x - Math.floor(x)
    return Math.floor(frac * (max - min + 1)) + min
  }

  const heartRate = Array.from({ length: 24 }).map((_, i) => ({
    t: `${i}`,
    bpm: random(70, 140),
  }))

  const sleep = [
    { name: '一', h: random(2, 8) },
    { name: '二', h: random(2, 8) },
    { name: '三', h: random(2, 8) },
    { name: '四', h: random(2, 8) },
    { name: '五', h: random(2, 8) },
  ]

  const steps = random(500, 12000)
  const stepGoal = 8000
  const stepsPercent = Math.min(100, Math.round((steps / stepGoal) * 100))

  const kcal = random(200, 1200)
  const kcalGoal = 1200
  const kcalPercent = Math.min(100, Math.round((kcal / kcalGoal) * 100))

  const trainingMin = random(20, 160)

  return { heartRate, sleep, steps, stepsPercent, kcal, kcalPercent, trainingMin }
}

const Data: React.FC = () => {
  const dates = [
    { day: '12', month: '11月' },
    { day: '13', month: '11月' },
    { day: '14', month: '11月' },
    { day: '15', month: '11月' },
    { day: '16', month: '11月' },
  ]
  const [active, setActive] = useState(0)
  const [data, setData] = useState(generateDashboardData(100))

  // Keep data stable per day by caching in localStorage
  useEffect(() => {
    const k = `dashboard:${dates[active].month}:${dates[active].day}`
    const cached = localStorage.getItem(k)
    if (cached) {
      try {
        setData(JSON.parse(cached))
        return
      } catch {}
    }
    const generated = generateDashboardData(100 + active * 37)
    localStorage.setItem(k, JSON.stringify(generated))
    setData(generated)
  }, [active])
  const [open, setOpen] = useState(false)
  const [shareOpen, setShareOpen] = useState(false)

  return (
    <div className="data-page">
      <div className="page-header">
        <div className="status-spacer" />
        <div className="title-row">
          <h1 className="page-title">活动</h1>
          <button className="icon-btn" aria-label="training" onClick={() => setOpen(true)}>
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
              <path d="M12 8v5l4 2" stroke="#6B7280" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              <path d="M3 12a9 9 0 1 0 9-9" stroke="#6B7280" strokeWidth="2" fill="none" />
              <path d="M3 3v6h6" stroke="#6B7280" strokeWidth="2" fill="none" />
            </svg>
          </button>
        </div>
      </div>

      <div className="date-scroll">
        {dates.map((d, i) => (
          <DatePill key={i} day={d.day} month={d.month} active={i === active} onClick={() => setActive(i)} />
        ))}
      </div>

      <div className="grid">
        <Card title="步数" icon={<span className="chip">步</span>}>
          <div className="center-row" style={{ height: 110 }}>
            <div className="chart-ring">
              <ResponsiveContainer width="100%" height="100%">
                <RadialBarChart innerRadius="72%" outerRadius="90%" data={[{ name: 'steps', value: data.stepsPercent }]} startAngle={90} endAngle={-270}>
                  <RadialBar dataKey="value" cornerRadius={10} fill="#FF6A2B" background={{ fill: '#F4F6F8' }} />
                </RadialBarChart>
              </ResponsiveContainer>
              <div className="ring-center">
                <div className="ring-text">
                  <div className="ring-number">{data.steps}</div>
                  <div className="ring-sub">步数</div>
                </div>
              </div>
            </div>
          </div>
        </Card>

        <Card title="心率" icon={<span className="chip chip-pink">心</span>}>
          <div style={{ width: '100%', height: 56 }}>
            <ResponsiveContainer>
              <LineChart data={data.heartRate} margin={{ left: 0, right: 0, top: 0, bottom: 0 }}>
                <Tooltip cursor={false} formatter={(v) => [`${v} bpm`, '心率']} labelFormatter={(l) => `${l}:00`} />
                <Line type="monotone" dataKey="bpm" stroke="#26C6A5" strokeWidth={2.5} dot={false} isAnimationActive />
              </LineChart>
            </ResponsiveContainer>
          </div>
          <div className="metric">
            <span className="metric-number">{data.heartRate[data.heartRate.length - 1].bpm}</span>
            <span className="metric-unit">bpm</span>
          </div>
        </Card>

        <Card title="训练" icon={<span className="chip">⏱</span>}>
          <div className="metric">
            <span className="metric-number">{data.trainingMin}</span>
            <span className="metric-unit">分钟</span>
          </div>
        </Card>

        <Card title="卡路里" icon={<span className="chip chip-warm">🔥</span>}>
          <div className="center-row" style={{ height: 110 }}>
            <div className="chart-ring">
              <ResponsiveContainer width="100%" height="100%">
                <RadialBarChart innerRadius="72%" outerRadius="90%" data={[{ name: 'kcal', value: data.kcalPercent }]} startAngle={90} endAngle={-270}>
                  <RadialBar dataKey="value" cornerRadius={10} fill="#FF6A2B" background={{ fill: '#F4F6F8' }} />
                </RadialBarChart>
              </ResponsiveContainer>
              <div className="ring-center">
                <div className="ring-text">
                  <div className="ring-number">{data.kcal}</div>
                  <div className="ring-sub">KCal</div>
                </div>
              </div>
            </div>
          </div>
        </Card>

        <Card title="睡眠" icon={<span className="chip">😴</span>}>
          <div style={{ width: '100%', height: 56 }}>
            <ResponsiveContainer>
              <BarChart data={data.sleep} margin={{ left: 0, right: 0, top: 0, bottom: 0 }}>
                <CartesianGrid vertical={false} stroke="#F3F4F6" />
                <XAxis dataKey="name" axisLine={false} tickLine={false} />
                <Tooltip formatter={(v) => [`${v} 小时`, '睡眠']} />
                <Bar dataKey="h" fill="#26C6A5" radius={[6, 6, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>
          <div className="metric">
            <span className="metric-number">{(data.sleep.reduce((a, b) => a + b.h, 0) / data.sleep.length).toFixed(1)}</span>
            <span className="metric-unit">小时</span>
          </div>
        </Card>

        <Card title="时间间隔" icon={<span className="chip chip-pink">⏰</span>}>
          <div className="metric">
            <span className="metric-number">{Math.max(10, 70 - data.trainingMin % 70)}</span>
            <span className="metric-unit">分钟</span>
          </div>
        </Card>
      </div>

      {/* Right side full-screen sheet */}
      <div className={`sheet-overlay${open ? ' open' : ''}`} onClick={() => setOpen(false)}>
        <div className={`sheet-right${open ? ' open' : ''}`} onClick={(e) => e.stopPropagation()}>
          <div className="sheet-header">
            <button className="sheet-back" onClick={() => setOpen(false)} aria-label="close">×</button>
            <div className="sheet-title">训练数据</div>
            <div className="sheet-action">
              <button className="icon-btn" aria-label="share" onClick={() => setShareOpen(true)}>
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                  <path d="M4 12v6a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-6" stroke="#6B7280" strokeWidth="2" strokeLinecap="round"/>
                  <path d="M12 16V4" stroke="#6B7280" strokeWidth="2" strokeLinecap="round"/>
                  <path d="M8 8l4-4 4 4" stroke="#6B7280" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </button>
            </div>
          </div>

          <div className="sheet-card">
            <div className="sheet-row">
              <div>
                <div className="sheet-kv-title">总时长</div>
                <div className="sheet-kv-value">{`${Math.floor(data.trainingMin / 60)}`.padStart(2, '0') + ':' + `${data.trainingMin % 60}`.padStart(2, '0')}:15</div>
              </div>
              <div>
                <div className="sheet-kv-title">平均心率</div>
                <div className="sheet-kv-value">{Math.round(data.heartRate.reduce((a, b) => a + b.bpm, 0) / data.heartRate.length)}<span className="unit"> bpm</span></div>
              </div>
            </div>
            <div className="sheet-row">
              <div>
                <div className="sheet-kv-title">活动卡路里</div>
                <div className="sheet-kv-value">{Math.max(300, Math.round(data.kcal * 0.6))}<span className="unit"> Kcal</span></div>
              </div>
              <div>
                <div className="sheet-kv-title">总卡路里</div>
                <div className="sheet-kv-value">{data.kcal}<span className="unit"> Kcal</span></div>
              </div>
            </div>
          </div>

          <div className="sheet-card">
            <div className="sheet-section-title">心率</div>
            <div style={{ width: '100%', height: 180 }}>
              <ResponsiveContainer>
                <BarChart data={data.heartRate.map(h => ({ name: h.t, v: h.bpm }))} margin={{ left: 0, right: 8, top: 8, bottom: 0 }}>
                  <CartesianGrid vertical={false} stroke="#EEF2F7" />
                  <XAxis dataKey="name" axisLine={false} tickLine={false} hide />
                  <Tooltip formatter={(v) => [`${v} bpm`, '心率']} labelFormatter={(l) => `${l}:00`} />
                  <Bar dataKey="v" fill="#FF6A2B" radius={[6, 6, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </div>
        </div>
      </div>

      {/* Bottom share sheet (inside popup) */}
      <div className={`sheet-overlay${shareOpen ? ' open' : ''}`} onClick={() => setShareOpen(false)}>
        <div className={`sheet-bottom${shareOpen ? ' open' : ''}`} onClick={(e) => e.stopPropagation()}>
          <div className="share-header">
            <div className="share-avatar">K</div>
            <div className="share-name">Koto</div>
          </div>
          <div className="share-input">这里输入内容...</div>
          <button className="share-submit" onClick={() => setShareOpen(false)}>分享到：</button>
          <div className="share-grid">
            <div className="share-item">
              <img src="/logImgs/weixin.png" alt="微信" className="share-icon"/>
              微信
            </div>
            <div className="share-item">
              <img src="/logImgs/wxpyq.png" alt="朋友圈" className="share-icon"/>
              朋友圈
            </div>
            <div className="share-item">
              <img src="/logImgs/lianjie.png" alt="复制链接" className="share-icon"/>
              复制链接
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

export default Data

